package org.zyzboole.base.encrypt.plugins;

import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.zyzboole.base.encrypt.properties.EnCryptProperties;
import org.zyzboole.base.encrypt.rewrite.EncryptPreParameterRewriter;
import org.zyzboole.base.encrypt.util.reflect.ReflectUtils;

import java.util.Properties;


/**
 * @Author: zyz
 * @Date: 2022/2/14 9:40
 * @description
 */
@Slf4j
@AllArgsConstructor
@Intercepts(
        {@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
        })
public class DataScopeInterceptor extends AbstractSqlParserHandler implements Interceptor {

    private final EncryptPreParameterRewriter rewriter;

    public DataScopeInterceptor(EnCryptProperties properties) {
        this.rewriter = new EncryptPreParameterRewriter(properties);
    }

    @Override
    @SneakyThrows
    public Object intercept(Invocation invocation) {
        Object proceed = invocation.proceed();
        ReflectUtils.reflectDecode(proceed, rewriter.getDispose());
        return proceed;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
